<template>
  <!-- 图片标注（广告牌）组件：在指定经纬度放置一张图片标注 -->
  <div style="display: none"></div>
</template>

<script setup>
import { inject, onMounted, onBeforeUnmount, watch, ref } from "vue";
import * as Cesium from "cesium";

const CESIUM_VIEWER_KEY = "cesiumViewer";
// 变量：注入的 viewer 引用（ref）
const viewerRef = inject(CESIUM_VIEWER_KEY, null);

// props：
// - position：位置（对象，单位：度/米），包含 lon/lat/height
// - image：图片 URL（需可跨域访问的 https 资源）
// - scale：缩放系数
// - verticalOrigin：垂直对齐（bottom/center/top）
// - show：是否显示
const props = defineProps({
  position: { type: Object, required: true },
  image: { type: String, required: true },
  scale: { type: Number, default: 1 },
  verticalOrigin: { type: String, default: "bottom" },
  show: { type: Boolean, default: true },
});

// 变量：当前图片标注实体引用
const entityRef = ref(null);

onMounted(() => {
  if (!viewerRef) return;
  const tryCreate = () => {
    if (!viewerRef.value) return false;
    createOrUpdate();
    return true;
  };
  if (!tryCreate()) {
    const stop = watch(() => viewerRef.value, (v) => {
      if (v) {
        createOrUpdate();
        stop();
      }
    });
  }
});

onBeforeUnmount(() => {
  const viewer = viewerRef && viewerRef.value;
  if (viewer && entityRef.value) viewer.entities.remove(entityRef.value);
  entityRef.value = null;
});

watch(() => ({ ...props }), () => createOrUpdate(), { deep: true });

function createOrUpdate() {
  const viewer = viewerRef && viewerRef.value;
  if (!viewer) return;
  const cartesian = Cesium.Cartesian3.fromDegrees(
    props.position.lon,
    props.position.lat,
    props.position.height ?? 0
  );
  const vOrigin =
    props.verticalOrigin === "top"
      ? Cesium.VerticalOrigin.TOP
      : props.verticalOrigin === "center"
      ? Cesium.VerticalOrigin.CENTER
      : Cesium.VerticalOrigin.BOTTOM;

  if (entityRef.value) {
    entityRef.value.position = cartesian;
    entityRef.value.billboard.image = props.image;
    entityRef.value.billboard.scale = new Cesium.ConstantProperty(props.scale);
    entityRef.value.billboard.verticalOrigin = vOrigin;
    entityRef.value.show = props.show;
  } else {
    entityRef.value = viewer.entities.add({
      show: props.show,
      position: cartesian,
      billboard: {
        // 对于跨域图片，尽量使用支持 CORS 的公开资源
        image: props.image,
        scale: props.scale,
        verticalOrigin: vOrigin,
      },
    });
  }
}

defineExpose({ getEntity: () => entityRef.value });
</script>

<style scoped>
</style>


